{js:kindeditor}
{js:my97date}
{set:$swfloadObject = new Swfupload('/seller/goods_img_upload');$swfloadObject->show($this->seller['seller_name'],$this->seller['seller_pwd']);}
{set:$seller_id = $this->seller['seller_id']}
<article class="module width_full">
	<header>
		<h3 class="tabs_involved">商品编辑</h3>

		<ul class="tabs" name="menu1">
			<li id="li_1" class="active"><a href="javascript:select_tab('1');">商品信息</a></li>
			<li id="li_2"><a href="javascript:select_tab('2');">描述</a></li>
			<li id="li_3"><a href="javascript:select_tab('3');">SEO优化</a></li>
		</ul>
	</header>

	<form action="{url:/seller/goods_update}" name="goodsForm" method="post">
		<input type="hidden" name="id" value="" />
		<input type='hidden' name="img" value="" />
		<input type='hidden' name="_imgList" value="" />
		<input type='hidden' name="callback" value="{echo:IUrl::getRefRoute()}" />

		<!--商品信息 开始-->
		<div class="module_content" id="table_box_1">
			<fieldset>
				<label>商品名称</label>
				<input name="name" type="text" value="" initmsg="商品名称填写正确" pattern="required" alt="商品名称不能为空" onblur="wordsPart()" />
			</fieldset>

			<fieldset>
				<label>关键词</label>
				<input type='text' name='search_words' value='' />
				<label class="tip">每个关键词最长为15个字符，超过后系统不予存储，每个词以逗号分隔</label>
			</fieldset>

			<fieldset>
				<label>所属分类</label>

				{if:isset($this->category) && $this->category}
				<ul class="select">
					{foreach:items=$this->category}
					<li><input type="checkbox" value="{$item['id']}" name="_goods_category[]" />{$item['name']}</li>
					{/foreach}
				</ul>
				{else:}
				<label class="tip">系统暂无商品分类</label>
				{/if}
			</fieldset>

			<fieldset>
				<label>商品排序</label>
				<input name="sort" type="text" pattern="int" value="99" />
			</fieldset>

			<fieldset>
				<label>计量单位显示</label>
				<input name="unit" type="text" value="千克"/>
			</fieldset>

			<fieldset>
				<label>基本数据</label>
				<table class="tablesorter clear">
					<thead id="goodsBaseHead"></thead>
					<tbody id="goodsBaseBody"></tbody>

					<!--商品标题模板-->
					<script id="goodsHeadTemplate" type='text/html'>
					<tr>
						<th>商品货号</th>
						<%var isProduct = false;%>
						<%for(var item in templateData){%>
						<%isProduct = true;%>
						<th><%=templateData[item]['name']%></th>
						<%}%>
						<th>库存</th>
						<th>市场价格</th>
						<th>销售价格</th>
						<th>成本价格</th>
						<th>重量(克)</th>
						<%if(isProduct == true){%>
						<th>操作</th>
						<%}%>
					</tr>
					</script>

					<!--商品内容模板-->
					<script id="goodsRowTemplate" type="text/html">
					<%var i=0;%>
					<%for(var item in templateData){%>
					<%item = templateData[item]%>
					<tr>
						<td><input class="small" name="_goods_no[<%=i%>]" pattern="required" type="text" value="<%=item['goods_no'] ? item['goods_no'] : item['products_no']%>" /></td>
						<%var isProduct = false;%>
						<%var specArrayList = parseJSON(item['spec_array'])%>
						<%for(var result in specArrayList){%>
						<%result = specArrayList[result]%>
						<input type='hidden' name="_spec_array[<%=i%>][]" value='{"id":"<%=result.id%>","type":"<%=result.type%>","value":"<%=result.value%>","name":"<%=result.name%>"}' />
						<%isProduct = true;%>
						<td>
							<%if(result['type'] == 1){%>
								<%=result['value']%>
							<%}else{%>
								<img class="img_border" width="30px" height="30px" src="{webroot:<%=result['value']%>}">
							<%}%>
						</td>
						<%}%>
						<td><input class="tiny" name="_store_nums[<%=i%>]" type="text" pattern="int" value="<%=item['store_nums']?item['store_nums']:100%>" /></td>
						<td><input class="tiny" name="_market_price[<%=i%>]" type="text" pattern="float" value="<%=item['market_price']%>" /></td>
						<td><input class="tiny" name="_sell_price[<%=i%>]" type="text" pattern="float" value="<%=item['sell_price']%>" /></td>
						<td><input class="tiny" name="_cost_price[<%=i%>]" type="text" pattern="float" empty value="<%=item['cost_price']%>" /></td>
						<td><input class="tiny" name="_weight[<%=i%>]" type="text" pattern="float" empty value="<%=item['weight']%>" /></td>
						<%if(isProduct == true){%>
						<td><a href="javascript:void(0)" onclick="delProduct(this);"><img src="{skin:images/main/icn_trash.png}" alt="删除" /></a></td>
						<%}%>
					</tr>
					<%i++;%>
					<%}%>
					</script>
				</table>
			</fieldset>

			<fieldset>
				<label>规格</label>
				<div class="box">
					<input type="button" onclick="selSpec()" value="添加规格" />
				</div>
			</fieldset>

			<fieldset>
				<label>商品模型</label>
				<select name="model_id" onchange="create_attr(this.value)">
					<option value="0">通用类型 </option>
					{query:name=model}
					<option value="{$item['id']}">{$item['name']}</option>
					{/query}
				</select>
			</fieldset>

			<fieldset id="properties" style="display:none">
				<label>扩展属性</label>
				<table class="tablesorter clear" id="propert_table">
				</table>

				<!--商品属性模板 开始-->
				<script type='text/html' id='propertiesTemplate'>
				<%for(var item in templateData){%>
				<%item = templateData[item]%>
				<%var valueItems = item['value'].split(',');%>
				<tr>
					<td>
						<%=item["name"]%>：
						<%if(item['type'] == 1){%>
							<%for(var tempVal in valueItems){%>
							<%tempVal = valueItems[tempVal]%>
								<input type="radio" name="attr_id_<%=item['id']%>" value="<%=tempVal%>" /><%=tempVal%>
							<%}%>
						<%}else if(item['type'] == 2){%>
							<%for(var tempVal in valueItems){%>
							<%tempVal = valueItems[tempVal]%>
								<input type="checkbox" name="attr_id_<%=item['id']%>[]" value="<%=tempVal%>"/><%=tempVal%>
							<%}%>
						<%}else if(item['type'] == 3){%>
							<select name="attr_id_<%=item['id']%>">
							<%for(var tempVal in valueItems){%>
							<%tempVal = valueItems[tempVal]%>
							<option value="<%=tempVal%>"><%=tempVal%></option>
							<%}%>
							</select>
						<%}else if(item['type'] == 4){%>
							<input type="text" name="attr_id_<%=item['id']%>" value="<%=item['value']%>" class="small" />
						<%}%>
					</td>
				</tr>
				<%}%>
				</script>
				<!--商品属性模板 结束-->
			</fieldset>

			<fieldset>
				<label>商品品牌</label>
				<select name="brand_id">
					<option value="0">请选择</option>
					{query:name=brand}
					<option value="{$item['id']}">{$item['name']}</option>
					{/query}
				</select>
			</fieldset>

			<fieldset>
				<label>商品状态</label>
				<div class="box">
					<input type='radio' name='is_del' value='3' checked="checked" />申请上架
					<input type='radio' name='is_del' value='2' />下架
				</div>
			</fieldset>

			<fieldset>
				<label>产品相册</label>
				<div class="box upload_btn">
					<span id='uploadButton'></span>
				</div>
				<label class="tip">可以上传多张图片，分辨率3000px以下，大小不得超过{echo:IUpload::getMaxSize()}</label>

				<div class="box" id="divFileProgressContainer" style="margin-bottom:10px;"></div>
				<div class="box" id="thumbnails"></div>

				<!--图片模板-->
				<script type='text/html' id='picTemplate'>
				<span class='pic'>
					<img onclick="defaultImage(this);" style="margin:5px; opacity:1;width:100px;height:100px" src="{webroot:<%=picRoot%>}" alt="<%=picRoot%>" /><br />
					<a href='javascript:void(0)' onclick="$(this).parent().remove();">删除</a>
				</span>
				</script>
			</fieldset>
		</div>
		<!--商品信息 结束-->

		<!--商品描述 开始-->
		<div class="module_content" id="table_box_2" style="display:none;">
			<fieldset>
				<label>详情采集：</label>
				<div class="box">
					<input type='text' id='collectUrl' class='large' />
					<input type="button" value="开始采集" onclick='collectAct();' />
					<label class="tip">部分详细资料属于异步加载，必须在前台页面可以正常显示</label>
				</div>
			</fieldset>

			<fieldset>
				<label>产品描述</label>
				<div class="clear" style="width:98%;margin:10px 10px;">
					<textarea id="content" name="content" style="width:100%;height:400px;"></textarea>
				</div>
			</fieldset>
		</div>
		<!--商品描述 结束-->

		<!--SEO 开始-->
		<div class="module_content" id="table_box_3" style="display:none;">
			<fieldset>
				<label>SEO关键词</label>
				<input name="keywords" type="text" value="" />
			</fieldset>

			<fieldset>
				<label>SEO描述</label>
				<textarea name="description" style="height:200px;"></textarea>
			</fieldset>
		</div>
		<!--SEO 结束-->

		<footer>
			<div class="submit_link">
				<input type="submit" class="alt_btn" value="确 定" onclick="return checkForm()" />
				<input type="reset" value="重 置" />
			</div>
		</footer>
	</form>

</article>

<script language="javascript">
//创建表单实例
var formObj = new Form('goodsForm');

//默认货号
var defaultProductNo = '{echo:goods_class::createGoodsNo()}';

$(function()
{
	initProductTable();

	//存在商品信息
	{if:isset($form)}
	var goods = {echo:JSON::encode($form)};

	var goodsRowHtml = template.render('goodsRowTemplate',{'templateData':[goods]});
	$('#goodsBaseBody').html(goodsRowHtml);

	formObj.init(goods);

	//模型选择
	$('[name="model_id"]').change();
	{else:}
	$('[name="_goods_no[0]"]').val(defaultProductNo);
	{/if}

	//存在货品信息,进行数据填充
	{if:isset($product)}
	var spec_array = {echo:$product[0]['spec_array']};
	var product    = {echo:JSON::encode($product)};

	var goodsHeadHtml = template.render('goodsHeadTemplate',{'templateData':spec_array});
	$('#goodsBaseHead').html(goodsHeadHtml);

	var goodsRowHtml = template.render('goodsRowTemplate',{'templateData':product});
	$('#goodsBaseBody').html(goodsRowHtml);
	{/if}

	//商品分类回填
	{if:isset($goods_category)}
	formObj.setValue('_goods_category[]',"{echo:join(';',$goods_category)}");
	{/if}

	//商品图片的回填
	{if:isset($goods_photo)}
	var goodsPhoto = {echo:JSON::encode($goods_photo)};
	for(var item in goodsPhoto)
	{
		var picHtml = template.render('picTemplate',{'picRoot':goodsPhoto[item].img});
		$('#thumbnails').append(picHtml);
	}
	{/if}

	//商品默认图片
	{if:isset($form['img']) && $form['img']}
	$('#thumbnails img[alt="{echo:$form['img']}"]').addClass('current');
	{/if}

	//编辑器载入
	KindEditorObj = KindEditor.create('#content',{"filterMode":false});
});

//初始化货品表格
function initProductTable()
{
	//默认产生一条商品标题空挡
	var goodsHeadHtml = template.render('goodsHeadTemplate',{'templateData':[]});
	$('#goodsBaseHead').html(goodsHeadHtml);

	//默认产生一条商品空挡
	var goodsRowHtml = template.render('goodsRowTemplate',{'templateData':[[]]});
	$('#goodsBaseBody').html(goodsRowHtml);
}

//删除货品
function delProduct(_self)
{
	$(_self).parent().parent().remove();
	if($('#goodsBaseBody tr').length == 0)
	{
		initProductTable();
	}
}

//提交表单前的检查
function checkForm()
{
	//整理商品图片
	var goodsPhoto = [];
	$('#thumbnails img').each(function(){
		goodsPhoto.push(this.alt);
	});
	if(goodsPhoto.length > 0)
	{
		$('input[name="_imgList"]').val(goodsPhoto.join(','));
		$('input[name="img"]').val($('#thumbnails img[class="current"]').attr('alt'));
	}
	return true;
}

//tab标签切换
function select_tab(curr_tab)
{
	$("form[name='goodsForm'] > div").hide();
	$("#table_box_"+curr_tab).show();
	$("ul[name=menu1] > li").removeClass('active');
	$('#li_'+curr_tab).addClass('active');
}

//添加规格
function selSpec()
{
	//货品是否已经存在
	if($('input:hidden[name^="_spec_array"]').length > 0)
	{
		alert('当前货品已经存在，无法进行规格设置。<p>如果需要重新设置规格请您手动删除当前货品</p>');
		return;
	}

	var tempUrl = '{url:/goods/search_spec/model_id/@model_id@/goods_id/@goods_id@/seller_id/$seller_id}';
	var model_id = $('[name="model_id"]').val();
	var goods_id = $('[name="id"]').val();

	tempUrl = tempUrl.replace('@model_id@',model_id);
	tempUrl = tempUrl.replace('@goods_id@',goods_id);

	art.dialog.open(tempUrl,{
		title:'设置商品的规格',
		okVal:'保存',
		ok:function(iframeWin, topWin)
		{
			//添加的规格
			var addSpecObject = $(iframeWin.document).find('[id^="vertical_"]');
			if(addSpecObject.length == 0)
			{
				initProductTable();
				return;
			}

			//开始遍历规格
			var specValueData = {};
			var specData      = {};
			addSpecObject.each(function()
			{
				$(this).find('input:hidden[name="specJson"]').each(function()
				{
					var json = $.parseJSON(this.value);
					if(!specValueData[json.id])
					{
						specData[json.id]      = {'id':json.id,'name':json.name,'type':json.type};
						specValueData[json.id] = [];
					}
					specValueData[json.id].push(json['value']);
				});
			});

			//生成货品的笛卡尔积
			var specMaxData = descartes(specValueData,specData);

			//从表单中获取默认商品数据
			var productJson = {};
			$('#goodsBaseBody tr:first').find('input[type="text"]').each(function(){
				productJson[this.name.replace(/^_(\w+)\[\d+\]/g,"$1")] = this.value;
			});

			//生成最终的货品数据
			var productList = [];
			for(var i = 0;i < specMaxData.length;i++)
			{
				var productItem = {};
				for(var index in productJson)
				{
					//自动组建货品号
					if(index == 'goods_no')
					{
						//值为空时设置默认货号
						if(productJson[index] == '')
						{
							productJson[index] = defaultProductNo;
						}

						if(productJson[index].match(/(?:\-\d*)$/) == null)
						{
							//正常货号生成
							productItem['goods_no'] = productJson[index]+'-'+(i+1);
						}
						else
						{
							//货号已经存在则替换
							productItem['goods_no'] = productJson[index].replace(/(?:\-\d*)$/,'-'+(i+1));
						}
					}
					else
					{
						productItem[index] = productJson[index];
					}
				}
				productItem['spec_array'] = specMaxData[i];
				productList.push(productItem);
			}

			//创建规格标题
			var goodsHeadHtml = template.render('goodsHeadTemplate',{'templateData':specData});
			$('#goodsBaseHead').html(goodsHeadHtml);

			//创建货品数据表格
			var goodsRowHtml = template.render('goodsRowTemplate',{'templateData':productList});
			$('#goodsBaseBody').html(goodsRowHtml);
		}
	});
}

//笛卡儿积组合
function descartes(list,specData)
{
	//parent上一级索引;count指针计数
	var point  = {};

	var result = [];
	var pIndex = null;
	var tempCount = 0;
	var temp   = [];

	//根据参数列生成指针对象
	for(var index in list)
	{
		if(typeof list[index] == 'object')
		{
			point[index] = {'parent':pIndex,'count':0}
			pIndex = index;
		}
	}

	//单维度数据结构直接返回
	if(pIndex == null)
	{
		return list;
	}

	//动态生成笛卡尔积
	while(true)
	{
		for(var index in list)
		{
			tempCount = point[index]['count'];
			temp.push({"id":specData[index].id,"type":specData[index].type,"name":specData[index].name,"value":list[index][tempCount]});
		}

		//压入结果数组
		result.push(temp);
		temp = [];

		//检查指针最大值问题
		while(true)
		{
			if(point[index]['count']+1 >= list[index].length)
			{
				point[index]['count'] = 0;
				pIndex = point[index]['parent'];
				if(pIndex == null)
				{
					return result;
				}

				//赋值parent进行再次检查
				index = pIndex;
			}
			else
			{
				point[index]['count']++;
				break;
			}
		}
	}
}

//根据模型动态生成扩展属性
function create_attr(model_id)
{
	$.getJSON("{url:/block/attribute_init}",{'model_id':model_id}, function(json)
	{
		if(json && json.length > 0)
		{
			var templateHtml = template.render('propertiesTemplate',{'templateData':json});
			$('#propert_table').html(templateHtml);
			$('#properties').show();

			//表单回填设置项
			{if:isset($goods_attr)}
			{set:$attrArray = array();}
			{foreach:items = $goods_attr}
			{set:$valArray = explode(',',$item);}
			{set:$attrArray[] = '"attr_id_'.$key.'[]":"'.join(";",$valArray).'"'}
			{set:$attrArray[] = '"attr_id_'.$key.'":"'.join(";",$valArray).'"'}
			{/foreach}
			formObj.init({{echo:join(',',$attrArray)}});
			{/if}
		}
		else
		{
			$('#properties').hide();
		}
	});
}

/**
 * 图片上传回调,handers.js回调
 * @param picJson => {'flag','img','list','show'}
 */
function uploadPicCallback(picJson)
{
	var picHtml = template.render('picTemplate',{'picRoot':picJson.img});
	$('#thumbnails').append(picHtml);

	//默认设置第一个为默认图片
	if($('#thumbnails img[class="current"]').length == 0)
	{
		$('#thumbnails img:first').addClass('current');
	}
}

/**
 * 设置商品默认图片
 */
function defaultImage(_self)
{
	$('#thumbnails img').removeClass('current');
	$(_self).addClass('current');
}

/**
 *分解名称关键词
 */
function wordsPart(){
	var goodsName = $('input[name="name"]').val();
	if(goodsName)
	{
		$.getJSON("{url:/goods/goods_tags_words}",{"content":goodsName},function(json)
		{
			if(json.result == 'success')
			{
				$('input[name="search_words"]').val(json.data);
			}
		});
	}
}

//开始采集商品详情
function collectAct()
{
	var collectUrl  = $('#collectUrl').val();

	if(!collectUrl)
	{
		alert("请选择采集器并且填写完整的商品详情页URL网址");
		return;
	}

	$.getJSON("{url:/goods/collect_goods_detail}",{"collectUrl":collectUrl},function(json)
	{
		if(json.result == 'success')
		{
			KindEditorObj.html(json.data);
			KindEditorObj.sync();
		}
		else
		{
			alert(json.msg);
		}
	});
}
</script>
